
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../model/baby.dart';

class BabySelector extends StatelessWidget {
  final Baby selectedBaby;
  final List<Baby> babies;
  final ValueChanged<Baby> onBabyChanged;

  const BabySelector({
    Key? key,
    required this.selectedBaby,
    required this.babies,
    required this.onBabyChanged,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => _showBabyPicker(context),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          CircleAvatar(
            radius: 20,
            backgroundImage: selectedBaby.avatarUrl != null
                ? FileImage(File(selectedBaby.avatarUrl!))
                : null,
            child: selectedBaby.avatarUrl == null
                ? Icon(Icons.child_care)
                : null,
          ),
          SizedBox(width: 8),
          Text(
            selectedBaby.name,
            style: Theme.of(context).textTheme.titleLarge,
          ),
          Icon(Icons.arrow_drop_down),
        ],
      ),
    );
  }

  void _showBabyPicker(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) => ListView.builder(
        shrinkWrap: true,
        itemCount: babies.length,
        itemBuilder: (context, index) {
          final baby = babies[index];
          return ListTile(
            leading: CircleAvatar(
              backgroundImage: baby.avatarUrl != null
                  ? FileImage(File(baby.avatarUrl!))
                  : null,
              child: baby.avatarUrl == null ? Icon(Icons.child_care) : null,
            ),
            title: Text(baby.name),
            subtitle: Text('${_calculateAge(baby.birthDate)}个月'),
            selected: baby.id == selectedBaby.id,
            onTap: () {
              onBabyChanged(baby);
              Navigator.pop(context);
            },
          );
        },
      ),
    );
  }

  String _calculateAge(DateTime birthDate) {
    final now = DateTime.now();
    final months = (now.year - birthDate.year) * 12 +
        now.month - birthDate.month;
    return months.toString();
  }
}